package com.mcode.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mcode.blog.dao.mapper.CategoryMapper;
import com.mcode.blog.dao.pojo.Category;
import com.mcode.blog.service.CategoryService;
import com.mcode.blog.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;


    /**
     * 根据id获取分类
     *
     * @param id
     * @return
     */
    @Override
    public CategoryVo findCategoryById(Long id) {
        Category category = categoryMapper.selectById(id);
        CategoryVo categoryVo = new CategoryVo();
        //因为category,categoryVo属性一样所以可以使用 BeanUtils.copyProperties
        BeanUtils.copyProperties(category, categoryVo);
        return categoryVo;
    }


    /**
     * 获取分类列表
     *
     * @return
     */
    @Override
    public List<CategoryVo> selectCate() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Category::getId);
        List<Category> categories = categoryMapper.selectList(queryWrapper);
        return copyList(categories);
    }


    /**
     * 分类详情
     *
     * @param id
     * @return
     */
    @Override
    public CategoryVo cateDetailById(Long id) {
        return copy(categoryMapper.selectById(id));
    }


    private List<CategoryVo> copyList(List<Category> categories) {
        List<CategoryVo> categoryVoList = new ArrayList<>();
        for (Category category : categories) {
            categoryVoList.add(copy(category));
        }
        return categoryVoList;
    }

    private CategoryVo copy(Category category) {
        CategoryVo categoryVo = new CategoryVo();
        BeanUtils.copyProperties(category, categoryVo);
        categoryVo.setId(String.valueOf(category.getId()));
        return categoryVo;
    }


}
